package com.ljfiction.book.Dialog;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.health.PackageHealthStats;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ljfiction.book.R;
import com.ljfiction.book.activitys.BaseActivity;
import com.ljfiction.book.manage.FileManage;
import com.ljfiction.book.tools.ImageTool;
import com.ljfiction.book.tools.PermissionUtils;
import com.ljfiction.book.tools.ScreenUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import rx.functions.Action1;

public class ImageDialog {


    private TextView takePhoto;

    private TextView choosePhoto;
    private String path;
    private Activity context;
    private Dialog bookimageDialog;
    private File file1;
    private Uri uriPath;

    public ImageDialog(final Activity context, final String path, Listener listener) {
        this.path = path;
        this.listener = listener;
        this.context = context;
        if (bookimageDialog == null) {
            bookimageDialog = new Dialog(context, R.style.ActionSheetDialogStyle);
        }
        //填充对话框的布局
        View vi = LayoutInflater.from(context).inflate(R.layout.bookimage_addbookdialog, null);
        takePhoto =  vi.findViewById(R.id.takePhoto);
        choosePhoto =  vi.findViewById(R.id.choosePhoto);
        takePhoto.setOnClickListener(new View.OnClickListener() {

            private Intent intent2;

            @Override
            public void onClick(View v) {
                if (!PermissionUtils.requestPermission(context, 4)) {
                    return;
                }
                bookimageDialog.dismiss();

                //调用快速拍照功能

                ImageTool.deleteFile(context.getExternalCacheDir() + "/" + path);
                intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                file1 = new File(context.getExternalCacheDir(), path);
                try {
                    if (file1.exists()) {
                        file1.delete();
                    }
                    file1.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //下面这句指定调用相机拍照后的照片存储的路径
               /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent2.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(context,"ljfiction.com.ljfiction.fileProvider", new File(FileManage.ImagePath, path));
                    intent2.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {
                    intent2.setDataAndType(Uri.fromFile(new File(FileManage.ImagePath, path)), "application/vnd.android.package-archive");
                    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }*/
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //intent2.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION|Intent.ACTION_CAMERA_BUTTON);
                    //Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileprovider",file1);
                    try {
                        Uri photoURI = FileProvider.getUriForFile(context, "com.ljfiction.book.fileprovider", file1);
                        intent2.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        context.startActivityForResult(intent2, 2);
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("cuowu"+e);
                    }
                } else {
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file1));
                    context.startActivityForResult(intent2, 2);
                }
            }
        });
        choosePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PermissionUtils.requestPermission(context, 7)) {
                    return;
                }
                bookimageDialog.dismiss();
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                /*下面这句话，与其它方式写是一样的效果，如果：
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType(""image *//**//**//**//*");设置数据类型如果要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"*/
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                context.startActivityForResult(intent, 1);
            }
        });

        //初始化控件
        //将布局设置给Dialog
        bookimageDialog.setContentView(vi);
        ViewGroup.LayoutParams layoutParams = vi.getLayoutParams();
        layoutParams.width = context.getResources().getDisplayMetrics().widthPixels;
        vi.setLayoutParams(layoutParams);
        bookimageDialog.getWindow().setGravity(Gravity.BOTTOM);
        bookimageDialog.getWindow().setWindowAnimations(R.style.ActionSheetDialogAnimation);
        bookimageDialog.setCancelable(true);
        bookimageDialog.show();

    }

    //imageType,0是封面长方形，1是头像正方形
    public void onActivityResult(final Intent data, int requestCode, final int imageType) {
        switch (requestCode) {
            // 如果是直接从相册获取
            case 1:
                if (data != null) {
                    Uri uri = data.getData();
                    ContentResolver cr = context.getContentResolver();
                    if(uri.getScheme().equals("content")) {//判断uri地址是以什么开头的

                    }else{
                       uri=getFileUri(uri);
                    }
                    startPhotoZoom(uri, imageType);
                }
                break;
            // 如果是调用相机拍照时
            case 2:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        RxPermissions.getInstance(context)
                                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)//这里填写所需要的权限
                                .subscribe(new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {
                                        if (aBoolean) {//true表示获取权限成功（注意这里在android6.0以下默认为true）
                                            File temp = new File(context.getExternalCacheDir() + "/" + path);
                                            Uri photoURI = FileProvider.getUriForFile(context.getApplicationContext(), context.getApplicationContext().getPackageName() + ".fileprovider", temp);
                                            startPhotoZoom(photoURI, imageType);
                                        } else {
                                        }
                                    }
                                });

                    } else {
                        File temp = new File(context.getExternalCacheDir() + "/" + path);
                        startPhotoZoom(Uri.fromFile(temp), imageType);

                    }
                break;
            // 取得裁剪后的图片
            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException
                 *
                 */

                setPicToView(data);
                break;
            default:
                break;

        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    //imageType,0是封面长方形，1是头像正方形
    public void startPhotoZoom(Uri uri, int imageType) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);

        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", true);
        // aspectX aspectY 是宽高的比例
        // outputX outputY 是裁剪图片宽高
        if (imageType == 0) {
            intent.putExtra("aspectX", 21);
            intent.putExtra("aspectY", 28);
            intent.putExtra("outputX", 210);
            intent.putExtra("outputY", 280);
        } else {
            intent.putExtra("aspectX", 21);
            intent.putExtra("aspectY", 21);

            intent.putExtra("outputX", 210);
            intent.putExtra("outputY", 210);
        }
        //uriPath = Uri.parse("file:///storage/emulated/0/Android/data/com.ljfiction.book/cache/" + System.currentTimeMillis()+"logoName.jpg");
        //将裁剪好的图输出到所建文件中
        uriPath = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "logoName.jpg");
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uriPath);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        context.startActivityForResult(intent, 3);
    }
    /*
    * 获取图片地址uri
    * */
    public Uri getFileUri(Uri uri){
        if (uri.getScheme().equals("file")) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(")
                        .append(MediaStore.Images.ImageColumns.DATA)
                        .append("=")
                        .append("'" + path + "'")
                        .append(")");
                Cursor cur = cr.query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[] { MediaStore.Images.ImageColumns._ID },
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur
                        .moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    //do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
       /* if (picdata!=null){
            Bundle extras = picdata.getExtras();
            if (extras != null) {
                Bitmap bitmap = extras.getParcelable("data");
                if (bitmap != null){
                    ImageTool.saveBitmap(bitmap, context.getExternalCacheDir(), path);
                    listener.getImage(bitmap);
                }
            }else {*/
                Bitmap bitmap = null;
                try {
                    bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uriPath));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                if (bitmap != null){
                    ImageTool.saveBitmap(bitmap, context.getExternalCacheDir(), path);
                    listener.getImage(bitmap);
                }
    }

    private Listener listener;


    public interface Listener {
        public void getImage(Bitmap photo);
    }

}
